<?php
declare(strict_types=1);

namespace app\model;

use support\Model;

class HttpLog extends Model
{
    protected $table = 'http_log';
    public $timestamps = false;

    protected static function pdo(): \PDO
    {
        $dsn = sprintf(
            'mysql:host=%s;port=%d;dbname=%s;charset=utf8mb4',
            env('DB_HOST', '127.0.0.1'),
            (int)env('DB_PORT', 3306),
            env('DB_DATABASE', 'saas_gps_service')
        );
        $pdo = new \PDO($dsn, env('DB_USERNAME', 'root'), env('DB_PASSWORD', ''), [
            \PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
            \PDO::ATTR_DEFAULT_FETCH_MODE => \PDO::FETCH_ASSOC,
            \PDO::ATTR_TIMEOUT => 5,
        ]);
        return $pdo;
    }

    public static function record(string $url, array $form, string $resp, int $ok, int $ms, string $err=''): void
    {
        $sql = "INSERT INTO http_log(url, form_data, resp_data, ok, cost_ms, err, created_at)
                VALUES(?,?,?,?,?,?,NOW())";
        $stmt = self::pdo()->prepare($sql);
        $stmt->execute([$url, json_encode($form, JSON_UNESCAPED_UNICODE), $resp, $ok, $ms, $err]);
    }
}